<template>
  <div style="margin-top: 20px;">
    <div style="text-align: right;padding-right: 20px;">
      <button_select_file @input="selectFile">
        {{ $t('label_import_excel') }}
        <i class="el-icon-upload2 el-icon--right"></i>
      </button_select_file>
      <el-button @click="downloadImportTemp" size="mini" type="primary">
        {{ $tt('label_download_import_template') }}<i class="el-icon-download el-icon--right"></i>
      </el-button>
    </div>

    <el-row>
      <el-col :span="1">
        <el-form-item :label="$t('label_pms_effective_time')">
          <div style="display: flex; align-items: center; gap: 4px;">
            <el-date-picker class="no-clear-input-text" v-model="formValue.versionStartTime" type="date"
              :placeholder="$t('label_pms_start_date')" :clearable="false" value-format="timestamp"
              :disabled="versionStartTimeDisabled">
            </el-date-picker>

            <span style="color: #606266;">{{ $t('label_link') }}</span>
            <el-date-picker class="no-clear-input-text" v-model="formValue.versionEndTime" type="date"
              :placeholder="$t('label_pms_start_date')" :clearable="false" value-format="timestamp">
            </el-date-picker>
          </div>
        </el-form-item>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="3">
        <el-form-item :label="$tt('label_pricing_unit')">
          <el-radio-group v-model="formValue.transportMainPrice.chargeType">
            <!-- 按计费重量 -->
            <el-radio-button label="CAL_WEIGHT">{{ $tt('PmsChargeTypeEnum__CAL_WEIGHT') }}</el-radio-button>
            <!-- 按实际重量 -->
            <el-radio-button label="WEIGHT">{{ $tt('PmsChargeTypeEnum__WEIGHT') }}</el-radio-button>
            <!-- 按体积 -->
            <el-radio-button label="VOLUME">{{ $tt('PmsChargeTypeEnum__VOLUME') }}</el-radio-button>
            <!-- 按密度 -->
            <el-radio-button label="DENSITY">{{ $tt('PmsChargeTypeEnum__DENSITY') }}</el-radio-button>
            <!-- 按货量/箱数 -->
            <el-radio-button label="BOX">{{ $tt('PmsChargeTypeEnum__BOX') }}</el-radio-button>
          </el-radio-group>
        </el-form-item>
      </el-col>
    </el-row>

    <el-row v-if="formValue.transportMainPrice.chargeType == 'CAL_WEIGHT'">
      <el-col :span="3">
        <el-form-item label="">
          <div class="price-cal-div-row">
            <!-- 计费重量 = Max（实际重量 KG , 体积  -->
            <div>{{ $tt('label_pms_cal_weight') }} = Max（{{ $tt('label_pms_real_weight') }} KG , {{
              $tt('label_volume')
            }} CBM * （ 100 * 100 * 100
            </div>
            <div>/</div>
            <div class="price-cal-col">
              <el-tooltip :content="$tt('label_pms_cal_weight_rate')" placement="top" effect="light">
                <input type="text" v-model="formValue.transportMainPrice.calWeightRate" class="price-edit-inner-input"
                  style="width: 90px;" />
              </el-tooltip>
            </div>
            <div> ））</div>
          </div>
        </el-form-item>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="3">
        <!-- 计价模式 -->
        <el-form-item :label="$tt('label_pms_price_type')">
          <el-radio-group v-model="formValue.transportMainPrice.priceType" style="padding-left: 10px;">
            <!-- 单价 -->
            <el-radio label="SINGLE"
              v-if="(formValue.transportMainPrice.chargeType !== 'DENSITY' && formValue.transportMainPrice.chargeType !== 'BOX')">
              {{ $tt('PmsTransportPriceTypeEnum__SINGLE') }}
            </el-radio>
            <!-- 续重-->
            <el-radio label="ADD"
              v-if="formValue.transportMainPrice.chargeType != 'VOLUME' && (formValue.transportMainPrice.chargeType !== 'DENSITY' && formValue.transportMainPrice.chargeType !== 'BOX')">
              {{ $tt('PmsTransportPriceTypeEnum__ADD') }}
            </el-radio>
            <!-- 总价 -->
            <el-radio label="TOTAL"
              v-if="(formValue.transportMainPrice.chargeType !== 'DENSITY' && formValue.transportMainPrice.chargeType !== 'BOX')">
              {{ $tt('PmsTransportPriceTypeEnum__TOTAL') }}
            </el-radio>
            <!-- 首重+续重 -->
            <el-radio label="MULTI_ADD"
              v-if="(formValue.transportMainPrice.chargeType == 'WEIGHT' || formValue.transportMainPrice.chargeType == 'CAL_WEIGHT')
                && (formValue.transportMainPrice.chargeType !== 'DENSITY' && formValue.transportMainPrice.chargeType !== 'BOX')">
              {{ $tt('PmsTransportPriceTypeEnum__MULTI_ADD') }}
            </el-radio>
            <el-radio label="RANGE_SINGLE"
              v-if="formValue.transportMainPrice.chargeType === 'DENSITY' || formValue.transportMainPrice.chargeType === 'BOX'">
              {{ $tt('PmsTransportPriceTypeEnum__RANGE_SINGLE') }}
            </el-radio>
          </el-radio-group>

          <el-button v-if="!batchEditPrice" v-show="editType" @click="dialogFormVisible = true" type="text" size="medium"
            style="margin-left: 160px;">
            <!-- 重量段配置 体积段 密度段 货量段配置 -->
            {{ getButtonLabel() }}
          </el-button>

        </el-form-item>
      </el-col>
    </el-row>

    <el-row
      v-if="(formValue.transportMainPrice.priceType == 'ADD') && (formValue.transportMainPrice.chargeType == 'CAL_WEIGHT' || formValue.transportMainPrice.chargeType == 'WEIGHT')">
      <el-col :span="3">
        <el-form-item :label="$tt('label_pricing_formula')">
          <!--（ {{ (formValue.chargeType == 'CAL_WEIGHT')?'计费重量':'实际重量'}} - 首重重量 kg ）x 续重价格 + 首重价格 -->
          （
          {{
            (formValue.transportMainPrice.chargeType == 'CAL_WEIGHT') ? $tt('label_pms_cal_weight') :
            $tt('label_pms_real_weight')
          }}
          - {{ $tt('label_pms_first_weight') }} {{ formValue.productGlobalConfig.weightUnit }} ）x {{
            $tt('label_pms_add_weight_price')
          }} +
          {{ $tt('label_pms_first_weight_price') }}
        </el-form-item>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="3" style="width: 100%;text-align: right;padding-bottom: 10px;">
<!--        <el-checkbox @change="configChange" v-model="firstWeightConfig">{{ $t('label_first_weight_get_value_config') }}</el-checkbox>-->
        <el-checkbox @change="configChange" v-model="binaryConfig">{{ $t('label_binary_config') }}</el-checkbox>
        <el-checkbox @change="configChange" v-model="operateFeeConfig">{{ $t('label_operat_fee_config') }}</el-checkbox>
        <el-checkbox v-model="batchEditPrice">{{ $t('label_separately_config') }}</el-checkbox>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="3" style="width: 100%;">
        <!-- 区间配置  -->
        <el-form-item :label="getFormPriceLabel()">
          <el-table :data="formValue.transportMainPrice.priceConfigs" style="width: auto;"
            class="line-weight-period-price-table" border>
            <!--物流分区 -->
            <el-table-column :label="$t('label_country')" prop="areaName" width="140" align="center" fixed>
              <template slot-scope="scope">
                {{ ' [' + scope.row.countryCode + '] ' + scope.row.areaName }}
                {{ scope.row.countryName }}
              </template>
            </el-table-column>
            <el-table-column :label="$t('label_price_cfg')" prop="pricePeriod" align="center">
              <template slot-scope="scope">
                <div class="flex_row " style="overflow: auto;margin:0 10px;">
                  <div v-for="(item, index) in scope.row.pricePeriod" class="flexuse">
                    <div class="flex_center">
                      {{ getElLabel(item, index) }}
                    </div>
                    <div>
                      <!-- 单价 -->
                      <div
                        v-if="formValue.transportMainPrice.chargeType !== 'DENSITY' && formValue.transportMainPrice.priceType !== 'MULTI_ADD'">
                        <div>{{ $t('label_unit_price') }}</div>
                        <el-input type="number" v-model.number="scope.row.pricePeriod[index].price" />
                      </div>



                      <!-- 首重+续重 -->
                      <div v-if="formValue.transportMainPrice.priceType === 'MULTI_ADD'"
                        style="display: flex;gap: 0 8px;  justify-content: space-between; ">
                        <div>
                          <div>{{ $t('label_first_weight_price') }}</div>
                          <el-input type="number" v-model.number="scope.row.pricePeriod[index].startPrice" />
                        </div>
                        <div>
                          <div>{{ $t('label_pms_added_price') }}</div>
                          <el-input type="number" v-model.number="scope.row.pricePeriod[index].addPrice" />
                        </div>
<!--                        <div v-show="firstWeightConfig">-->
<!--                          <div>{{ $t('label_first_weight_get_value') }}</div>-->
<!--                          <el-input type="number" v-model.number="scope.row.pricePeriod[index].customFirstWeight" />-->
<!--                        </div>-->
                      </div>

                      <!-- 按密度 -->
                      <div v-if="formValue.transportMainPrice.chargeType === 'DENSITY'"
                        style="display: flex; justify-content: space-between;gap:8px ">
                        <div>
                          <div>{{ $t('label_unit_price') }}</div>
                          <el-input type="number" v-model.number="scope.row.pricePeriod[index].price" />
                        </div>
                        <div>
                          <div>{{ $t('label_unit') }}</div>
                          <el-select v-model="scope.row.pricePeriod[index].unit">
                            <el-option v-for="(item, index) in densityOptions" :key="item.value" :label="item.label"
                              :value="item.value">
                            </el-option>
                          </el-select>
                        </div>
                      </div>
                      <!-- 进制配置 -->
                      <div v-if="binaryConfig">
                        <div>{{ $t('label_binary') }}</div>
                        <el-input type="number" v-model.number="scope.row.pricePeriod[index].scale" />
                      </div>
                      <!-- 操作费配置 -->
                      <div v-if="operateFeeConfig">
                        <div>{{ $t('label_operate_fee') }}</div>
                        <el-input type="number" v-model.number="scope.row.pricePeriod[index].otherAttachPrice" />
                      </div>
                    </div>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column :label="$t('label_operate')" prop="areaName" width="160" align="center" fixed="right"
              v-if="batchEditPrice">
              <template slot-scope="{row}">
                <el-button @click="dialogFormVisible = true; tempRowObj = row" type="text" size="medium">
                  <!-- 重量段配置 体积段 密度段 货量段配置 -->
                  {{ getButtonLabel() }}
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <span style="color: #666; line-height: 32px; margin-top: 10px;height: 40px; "><i class="el-icon-warning"
              style="margin-right: 6px;"></i>
            {{ getChargeLabel() }}
            {{ $t('tip_pms_product4', [getChargeLabel(), getChargeLabel(), getChargeLabel()]) }}

          </span>
          <br />
          <span v-if="formValue.transportMainPrice.chargeType === 'DENSITY'"
            style="color: #666; line-height: 32px; margin-top: 10px;height: 40px; ">
            <i class="el-icon-warning" style="margin-right: 6px;"></i>{{ $t('tip_pms_product1') }}</span>
        </el-form-item>
      </el-col>
    </el-row>

    <!-- 重量单位 -->
    <el-row>
      <el-col>
        <el-form-item :label="$tt('label_pms_weight_unit')">
          <ex_super_input v-model="formValue.productGlobalConfig.weightUnit" type="select" enum="PmsGlobalWeightUnitEnum"
            style="width: 100%;"></ex_super_input>
        </el-form-item>
      </el-col>
    </el-row>

    <!-- 结算币种 -->
    <el-row>
      <el-col>
        <el-form-item :label="$tt('label_pms_product_currency')">
          <fms-currency-choose v-model="formValue.transportMainPrice.currencyType"
            style="width:100%;"></fms-currency-choose>
        </el-form-item>
      </el-col>
    </el-row>


    <!-- 扣费节点 -->
    <template v-if="showCostPoint">
      <el-row>
        <el-col>
          <el-form-item :label="$tt('label_pms_service_point')">
            <pms-price-point v-model="formValue.transportMainPrice.pricePoint" :productType="productType"
              style="width:100%;"></pms-price-point>
          </el-form-item>
        </el-col>
      </el-row>
    </template>

    <!-- 物流杂费配置 -->
    <el-row style="margin-bottom: 20px;">
      <el-col :span="3">
        <el-form-item :label="$tt('label_pms_transport_other_cfg')">
          <!--          <ex_header_spiler :title="$tt('label_pms_transport_other_cfg')"></ex_header_spiler>-->
          <div style="display: flex; ">
            <!-- 费用项名称 -->
            <div style="width: 160px; margin-right: 10px; text-align: center; ">
              {{ $tt('label_pms_service_cost_name') }}
            </div>
            <!-- 计费方式 -->
            <div style="width: 160px;  margin-right: 10px; text-align: center;  ">
              {{ $tt('label_pms_service_charge_type') }}
            </div>
            <!-- 扣费节点 -->
            <div style="width: 160px;  margin-right: 10px;  text-align: center; " v-if="showCostPoint">
              {{ $tt('label_pms_service_point') }}
            </div>
            <!-- 扣费币种 -->
            <div style="width: 160px;  margin-right: 10px;  text-align: center; ">
              {{ $tt('label_pms_service_currency') }}
            </div>
            <!-- 计费金额 -->
            <div style="width: 170px;  margin-right: 10px;  text-align: center; ">
              {{ $tt('label_pms_service_amount') }}
            </div>
            <div style="width: 90px;  margin-right: 10px;  text-align: center; ">
              <!--添加 -->
              <el-button size="medium" @click="addNewOtherPrice" v-show="editType">
                {{ $tt('label_new') }}
              </el-button>
            </div>
          </div>

          <div style="display: flex; line-height: 42px;" v-for="(item, additaonalIndex) in formValue.additionPrices">

            <div style="width: 160px;  margin-right: 10px; ">
              <el-select v-model="item.serviceCode" :placeholder="$tt('tip_please_select')" style="width: 100%;"
                clearable>
                <el-option v-for="item in serviceCostArr" :key="item.serviceCode" :label="item.serviceName"
                  :value="item.serviceCode">
                </el-option>
              </el-select>
            </div>

            <div style="width: 160px;  margin-right: 10px; ">
              <ex_super_input v-model="item.chargeType" type="select" enum="PmsChargeTypeEnum"></ex_super_input>
            </div>

            <div style="width: 160px;  margin-right: 10px; " v-if="showCostPoint">
              <pms-price-point v-model="item.pricePoint" :productType="productType"></pms-price-point>
            </div>

            <div style="width: 160px;  margin-right: 10px; ">
              <fms-currency-choose v-model="item.currencyType" style="width: 100%;"></fms-currency-choose>
            </div>

            <div style="width: 170px;  margin-right: 10px; " v-if="item.chargeType !== 'EXPRESSION'">
              <el-input v-model="item.price" style="width: 90px; " class="input-align-right"></el-input>&nbsp;{{
                item.chargeType ? $tt('PmsPriceUnitEnum__' + chargeTypeMap[item.chargeType]) : ''
              }}&nbsp;
            </div>

            <div style="width: 170px;  margin-right: 10px; text-align: center; " v-if="item.chargeType === 'EXPRESSION'">
              <el-button type="text" @click="showExpressionDialog(item, additaonalIndex)">{{ $t('label_expression_config')
              }}</el-button>
            </div>

            <div style="width: 90px;  margin-right: 10px;  text-align: center; color: #666; cursor: pointer; ">
              <!-- 删除 -->
              <ex-confirm-button v-show="editType" :label="$tt('label_delete')"
                @afterOperationDone="formValue.additionPrices.splice(additaonalIndex, 1)"></ex-confirm-button>
            </div>
          </div>

        </el-form-item>
      </el-col>
    </el-row>


    <!-- 价卡修改记录  -->
    <el-row style="margin-bottom: 100px;" v-if="showCostPoint">
      <el-col :span="3">
        <el-form-item :label="$t('label_pms_price_history')">

          <el-timeline style="margin-top: 10px;" class="transprot-price-time-line">
            <el-timeline-item v-for="(item, index) in  priceTagHistory" :key="index"
              :timestamp="$dateFormat(item.versionPriceTag)">
              {{ item.creator }}

              <ex-button-delete style="position: absolute; left: 220px;" :message="$t('label_switch_price_version_tip')"
                :label="$t('label_switch_price_version')" byAction
                :delAction="() => { switchPriceVersion(item.id) }"></ex-button-delete>
            </el-timeline-item>
          </el-timeline>

        </el-form-item>
      </el-col>
    </el-row>

    <!-- 表达式弹窗 -->
    <expression-edit-dialog ref="expression" @save="saveExpression">
    </expression-edit-dialog>

    <!-- 体积段配置  重量段配置  密度段配置  货量段配置-->
    <el-dialog
      :title="formValue.transportMainPrice.chargeType == 'VOLUME' ? $tt('label_pms_volume_range_cfg') : $tt('label_pms_weight_range_cfg')"
      :visible.sync="dialogFormVisible" width="1000px">
      <el-form inline>
        <!-- 生成方式 -->
        <el-form-item :label="$tt('label_pms_generate_type')" labelWidth="90px">
          <el-radio-group v-model="weightForm.genType">
            <!-- 按步长 -->
            <el-radio-button label="byStep">{{ $tt('label_pms_by_step') }}</el-radio-button>
            <!-- 按分段数量 -->
            <el-radio-button label="byNumber">{{ $tt('label_pms_by_split_num') }}</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <!-- 最大体积 CBM': '最大重量 Kg -->
        <el-form-item
          :label="formValue.transportMainPrice.chargeType == 'VOLUME' ? $tt('label_pms_max_volumn') + ' CBM' : $tt('label_pms_max_weight') + formValue.productGlobalConfig.weightUnit">
          <el-input-number v-model="weightForm.maxWeight" style="width: 140px;" :min="1" :max="100000"></el-input-number>
        </el-form-item>
        <!-- 分段数量 -->
        <el-form-item :label="$tt('label_pms_split_nums')" v-if="weightForm.genType == 'byNumber'">
          <el-input-number v-model="weightForm.number" style="width: 140px;" :min="1" :max="100"></el-input-number>
        </el-form-item>
        <!-- 步长体积 CBM': '步长重量 Kg -->
        <el-form-item
          :label="formValue.transportMainPrice.chargeType == 'VOLUME' ? $tt('label_pms_step_volume') + ' CBM' : $tt('label_pms_stop_weight') + formValue.productGlobalConfig.weightUnit"
          v-if="weightForm.genType == 'byStep'">
          <el-input v-model="weightForm.step" style="width: 100px;"></el-input>
        </el-form-item>

        <!-- 生成 -->
        <el-button @click="generateWeights">{{ $tt('label_pms_gernate') }}</el-button>

        <br />
        <!-- 体积段配置   重量段配置 -->
        <el-form-item
          :label="formValue.transportMainPrice.chargeType == 'VOLUME' ? $tt('label_pms_volume_range_cfg') : $tt('label_pms_weight_range_cfg')"
          labelWidth="90px">
          <div style="width: 810px; display: flex; flex-direction: row; flex-wrap: wrap;">
            <div v-for="(item, index) in weightArray" :key="index" class="weightRangeWrap"
              @mouseover="item.showRemove = true" @mouseleave="item.showRemove = false">
              <i v-show="item.showRemove" @click="weightArrayAdd(index)" class="el-icon-circle-plus"
                style="position: absolute; top: 0px; left: 0px; cursor: pointer; color: #67C23A;z-index: 10;"></i>
              <el-input type="number" v-model.number="item.value" class="weightRangeInput"/>
              <i v-if="index > 0 && index < weightArray.length - 1" v-show="item.showRemove"
                @click="weightArray.splice(index, 1)" class="el-icon-remove"
                style="position: absolute; top: 0px; right: 0px; cursor: pointer; color: #d74343; z-index: 10;"></i>
            </div>
          </div>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer" style="display: flex; justify-content: space-between; ">
        <span style="color: orangered; padding-left: 96px;">
          <i class="el-icon-warning"></i>
          <template v-if="formValue.transportMainPrice.chargeType == 'VOLUME'">
            {{ $tt('label_pms_pms_warning_1') }}
          </template>
          <template v-else>{{ $tt('label_pms_pms_warning_2') }}</template>
        </span>
        <div>
          <el-button @click="dialogFormVisible = false">{{ $tt('label_cancel') }}</el-button>
          <el-button type="primary" @click="confirmWeight">{{ $tt('label_save') }}</el-button>
        </div>
      </div>

    </el-dialog>

  </div>
</template>
<script>
import ExcelJS from '@/asset/exceljs.bare.min.js'

import FmsCurrencyChoose from '@/component/fms/fms-currency-choose.vue'
import PmsPricePoint from '@/component/pms/pms-price-point.vue'
import ExpressionEditDialog from "@/component/fms/expression-edit-dialog.vue";

export default {
  // title: "新增" + moduleName,
  components: { FmsCurrencyChoose, PmsPricePoint, ExpressionEditDialog },
  mixins: [],
  data() {

    return {
      // 首重取值配置
      firstWeightConfig:false,
      // 单独配置
      batchEditPrice: false,
      // 进制配置
      binaryConfig: false,
      // 操作费配置
      operateFeeConfig: false,

      "dialogFormVisible": false,
      tempRowObj: {},

      "weightForm": {
        "genType": "byNumber",
        "maxWeight": 100,
        "number": 20,
        "step": 0.5
      },
      // 重量、体积分段
      "weightArray": [{
        "showRemove": false,
        "value": 0
      }, {
        "showRemove": false,
        "value": 1
      }, {
        "showRemove": false,
        "value": 10
      }, {
        "showRemove": false,
        "value": 50
      }, {
        "showRemove": false,
        "value": 100
      }],

      densityOptions: [{
        value: 'weight',
        label: 'kg'
      }, {
        value: 'volume',
        label: 'CBM'
      }],

      "editWeightTableHead": [],
      "editWeightTableRows": [],
      "samplePricePeriod": [],

      "operateType": "",

      "formValue": {
        // "daterange": [],
        "versionId": "",
        "versionName": "",
        "versionStartTime": "",
        "versionEndTime": "",
        "priceVersionTime": "",
        "versionType": "",
        "transportMainPrice": {
          "priceType": "WEIGHT",
          "productType": "first",
          "chargeType": "CAL_WEIGHT",
          "calWeightRate": 6000,
          "priceConfigs": []
        },
        "additionPrices": [],
        "productGlobalConfig": {
          "weightUnit": 'kg',
        }
      },

      // 物流分区
      'areaArray': [],

      // 单位map
      "chargeTypeMap": {},

      // 杂费
      "serviceCostArr": [],

      // 版本记录
      "priceTagHistory": [],

      // 国家数据
      countryData: [],
      // 进制配置
      "weightRangeFrom": {
        "priceType": '',
        "priceRanges": []
      },
    };
  },

  props: {
    // 是否显示扣费节点配置项
    'showCostPoint': {
      type: Boolean,
      default: false
    },

    'productType': {
      type: String,
      default: ''
    },

    'inputValue': {
      type: Object,
      default: () => {
      }
    },

    'versionStartTimeDisabled': {
      type: Boolean,
      default: false
    },

    'priceVersionId': {
      type: String,
      default: '-1'
    },

    'editType': {
      type: Boolean,
      default: true
    }

  },
  created() {
    let _this = this

    // 获取单位相关映射
    _this.$ajax({
      url: '/fms-api/product/PriceUnitRpc/getPriceUnitMap.json',
      success: (res) => {
        if (res && res.data) {
          _this.chargeTypeMap = res.data
        }
      }
    });

    // 获取可选费用项
    _this.$ajax({
      url: '/fms-api/agent/AgentServiceCostRpc/selectEnable.json',
      success: (res) => {
        if (res && res.data && res.data.rows) {
          _this.serviceCostArr = res.data.rows
        }
      }
    });

    _this.formValue = { ..._this.formValue, ..._this.inputValue }
    _this.initForm();

    _this.loadPriceVersionTags(_this.priceVersionId)

  },
  mounted() {

  },
  complete: {
  },
  watch: {

    'formValue.transportMainPrice.chargeType'(val, old) {
      // 计价单位为体积时，计价模式只支持 单价、总价
      if (val == 'VOLUME') {
        if (this.formValue.transportMainPrice.priceType == 'MULTI_ADD' || this.formValue.transportMainPrice.priceType == 'ADD') {
          this.formValue.transportMainPrice.priceType = 'TOTAL'
        }
        return
      }
      if (val === 'BOX' || val === 'DENSITY') {
        this.formValue.transportMainPrice.priceType = 'RANGE_SINGLE'

        this.rebuildDensityOptions()
      }

    },

    'formValue.versionStartTime'(val, old) {
      if (this.formValue.versionStartTime != '' && this.formValue.versionEndTime != '') {
        this.$emit('dateRangeChange', [this.formValue.versionStartTime, this.formValue.versionEndTime])
      }

    },
    'formValue.versionEndTime'(val, old) {
      if (this.formValue.versionStartTime != '' && this.formValue.versionEndTime != '') {
        this.$emit('dateRangeChange', [this.formValue.versionStartTime, this.formValue.versionEndTime])
      }
    },
  },

  methods: {
    saveExpression(expressionForm) {
      let index = expressionForm.index

      this.$set(this.formValue.additionPrices[index], 'remark', expressionForm.remark)
      this.$set(this.formValue.additionPrices[index], 'expressionFunction', expressionForm.expressionFunction)
    },
    showExpressionDialog(item, index) {
      this.$refs['expression'].showDialog(item, index)
    },
    rebuildDensityOptions() {
      if (this.formValue.transportMainPrice.chargeType === 'DENSITY') {
        this.densityOptions = [{
          value: 'weight',
          label: this.formValue.transportMainPrice.currencyType + "/" + this.formValue.productGlobalConfig.weightUnit
        }, {
          value: 'volume',
          label: this.formValue.transportMainPrice.currencyType + "/" + 'CBM'
        }]
      }
    },
    addNewOtherPrice() {
      if (!this.formValue.additionPrices) {
        this.formValue.additionPrices = []
      }
      this.formValue.additionPrices.push({ 'costName': '', costType: 'order', price: '0' })
    },

    updateForm(formValue) {
      this.formValue = formValue
      this.initForm()
    },

    updateArea(areaArray) {
      this.initForm()
      let _this = this
      if (!areaArray || areaArray.length === 0) {
        _this.$message({
          type: 'error',
          message: this.$tt('tip_least_one_select_logistics_part')
        })
        return
      }

      let priceConfigMap = {}
      this.formValue.transportMainPrice.priceConfigs.forEach(r => {
        priceConfigMap[r.areaId + ''] = r
      })

      let newPriceConfigArr = []

      areaArray.forEach(r => {

        let row = priceConfigMap[r.id + '']
        if (row) {
          row["areaId"] = r.id
          row["areaCode"] = r.areaCode
          row["areaName"] = r.name
          row["countryCode"] = r.countryCode

        } else {
          row = {
            "areaId": r.id,
            "areaName": r.name,
            "areaCode": r.areaCode,
            "countryCode": r.countryCode,
            "singlePrice": 100,
            "pricePeriod": JSON.parse(JSON.stringify(this.samplePricePeriod))
          }
        }
        newPriceConfigArr.push(row)
      })
      this.$set(this.formValue.transportMainPrice, 'priceConfigs', newPriceConfigArr)
    },

    getFormData() {
      return this.formValue
    },

    async initForm() {

      this.editWeightTableHead = []

      if (this.formValue.transportMainPrice.priceConfigs && this.formValue.transportMainPrice.priceConfigs.length > 0) {

        // get 国家数据
        let areaIds = []
        this.formValue.transportMainPrice.priceConfigs.forEach(r => {
          areaIds.push(r.areaId)
        })
        await this.$ajax({
          url: '/tms-api/base/TmsLogisticsAreaInfoRpc/selectLabel.json',
          type: 'json',
          data: {
            logisticsSubIdList: areaIds
          },
          success: (res) => {
            if (res && res.data && res.data.rows) {
              this.countryData = res.data.rows
              res.data.rows.forEach(r => {
                this.formValue.transportMainPrice.priceConfigs.forEach(r2 => {
                  if (r.id === r2.areaId) {
                    this.$set(r2, "countryCode", r.countryCode)
                    this.$set(r2, "countryName", r.countryName)
                  }
                })
              })
            }
          }
        });

        this.$set(this.formValue.transportMainPrice, 'priceConfigs', this.formValue.transportMainPrice.priceConfigs)


        let weightArray = []
        let firstRow = this.formValue.transportMainPrice.priceConfigs[0].pricePeriod

        if (firstRow && firstRow.length > 0) {
          firstRow.forEach(e => {
            this.editWeightTableHead.push({
              id: 'id_' + Math.random(),
              value: e.start + '-' + e.end
            })
            weightArray.push({
              "showRemove": false,
              "value": e.start
            })
          })
          weightArray.push({
            "showRemove": false,
            "value": firstRow[firstRow.length - 1].end
          })
        }
        this.samplePricePeriod = firstRow
        this.weightArray = weightArray

        // 根绝数据适配编辑模式
        this.formValue.transportMainPrice.priceConfigs.forEach((item, index) => {
          let pricePeriod = item.pricePeriod
          // 判断进制配置和操作费配置是否需要勾选 如果都勾选了就不需要在循环了
          if (!this.binaryConfig || !this.operateFeeConfig) {
            for (let j = 0; j < pricePeriod.length; j++) {
              const pricePeriodItem = pricePeriod[j];
              if (pricePeriodItem.scale) {
                this.binaryConfig = true
              }
              if (pricePeriodItem.otherAttachPrice) {
                this.operateFeeConfig = true
              }

              if (pricePeriodItem.customFirstWeight) {
                this.firstWeightConfig = true
              }

              // 如果都勾选了就不需要在循环了
              if (this.binaryConfig && this.operateFeeConfig&&this.firstWeightConfig) {
                break
              }

            }
          }
          if (index == 0) {
            return
          }
          if (pricePeriod.length !== firstRow.length) {
            this.batchEditPrice = true
            return
          }

        }
        )
      }
    },

    getFormPriceLabel() {

      // 密度
      if (this.formValue.transportMainPrice.chargeType === 'DENSITY') {
        return this.$tt('label_pms_density_range_cfg')
      }
      // 货量
      if (this.formValue.transportMainPrice.chargeType === 'BOX') {
        return this.$tt('label_pms_gross_cargo_range_cfg')
      }

      if (this.formValue.transportMainPrice.priceType == 'ADD') {
        return this.$tt('label_pms_add_price_cfg')
      }
      if (this.formValue.transportMainPrice.priceType == 'TOTAL') {
        return this.$tt('label_pms_total_price_cfg')
      }
      if (this.formValue.transportMainPrice.priceType == 'MULTI_ADD') {
        return this.$t('label_pms_first_add_weight_cfg')
      }
      if (this.formValue.transportMainPrice.priceType == 'SINGLE') {
        return this.$t('label_unit_price_cfg')
      }

      return ''
    },

    getChargeLabel() {
      if (this.formValue.transportMainPrice.chargeType == 'WEIGHT' || this.formValue.transportMainPrice.chargeType == 'CAL_WEIGHT') {
        return this.$t('label_weight')
      }
      if (this.formValue.transportMainPrice.chargeType == 'VOLUME') {
        return this.$t('label_volume')
      }
      // 密度
      if (this.formValue.transportMainPrice.chargeType === 'DENSITY') {
        return this.$t('label_pms_density')
      }
      // 货量
      if (this.formValue.transportMainPrice.chargeType === 'BOX') {
        return this.$t('label_pms_gross_cargo')
      }
    },

    getElLabel(item, index) {

      item.value = item.start + '-' + item.end

      let weightUnit = this.formValue.productGlobalConfig.weightUnit

      let boxUnit = 'box'

      let volumeUnit = 'CBM'

      let unit = ''

      if (this.formValue.transportMainPrice.chargeType == 'WEIGHT' || this.formValue.transportMainPrice.chargeType == 'CAL_WEIGHT') {
        unit = weightUnit
      }
      if (this.formValue.transportMainPrice.chargeType == 'VOLUME') {
        unit = volumeUnit
      }
      if (this.formValue.transportMainPrice.chargeType == 'BOX') {
        unit = boxUnit
      }
      if (this.formValue.transportMainPrice.chargeType == 'DENSITY') {
        unit = weightUnit + '/' + volumeUnit
      }
      if (this.formValue.transportMainPrice.chargeType === 'BOX' || this.formValue.transportMainPrice.chargeType === 'DENSITY') {
        return `${item.value}${unit}`
      }
      // 续重 - 首重价
      if (index == 0 && (this.formValue.transportMainPrice.priceType == 'ADD' || this.formValue.transportMainPrice.priceType == 'SINGLE')) {
        let tmps = item.value.split('-')
        return `${tmps[1]}${unit} ` + this.$tt('label_pms_under_price')
      }
      // 总价
      else if (this.formValue.transportMainPrice.priceType == 'TOTAL') {
        return `${item.value}${unit} ` + this.$tt('label_pms_total_price')
      }
      // 续重 - 续重价
      else if (this.formValue.transportMainPrice.priceType == 'ADD') {
        return `${item.value}${unit} ` + this.$tt('label_pms_added_price')
      }
      // 首重 + 续重
      else if (this.formValue.transportMainPrice.priceType == 'MULTI_ADD') {

        return `${item.value}${unit}`

      } else if (this.formValue.transportMainPrice.priceType == 'SINGLE') {

        return `${item.value}${unit}`
      }

      return item.value
    },

    confirmWeight() {

      let editWeightTableHead = []

      let samplePricePeriod = []

      // $tt('PmsTransportPriceTypeEnum__MULTI_ADD')
      if (this.formValue.transportMainPrice.priceType == 'MULTI_ADD' && this.weightArray.length <= 2) {
        this.$message({
          type: 'error',
          message: this.$t('tip_pms_product2')
        })
        return
      }

      this.weightArray = this.weightArray.filter(_=>_.value||_.value===0)

      for (let i = 0; i < this.weightArray.length; i++) {

        let e = this.weightArray[i].value

        let isNum = this.$isNumber(e)

        if (!isNum) {
          this.$message({
            'type': 'error',
            'message': e + ' is not a number'
          })

          return
        }

        if (i == 0) {
          continue;
        }

        if (parseFloat(this.weightArray[i].value) <= parseFloat(this.weightArray[i - 1].value)) {
          this.$message({
            'type': 'error',
            'message': this.$t('tip_pms_product3')
          })
          return
        }
        editWeightTableHead.push({
          id: 'id_' + Math.random(),
          value: this.weightArray[i - 1].value + '-' + this.weightArray[i].value
        })

        samplePricePeriod.push({
          "start": this.weightArray[i - 1].value,
          "end": this.weightArray[i].value,
          "price": 10,
          "startPrice": 10,
          "addPrice": 10,
          "customFirstWeight": '',
          "unit": 'weight',
          "scale": '',
          "otherAttachPrice": ''
        })
      }

      this.samplePricePeriod = samplePricePeriod

      // 首重值
      // this.firstWeightValue = this.weightArray[1].value

      this.editWeightTableHead = editWeightTableHead

      if (!this.batchEditPrice) {
        this.formValue.transportMainPrice.priceConfigs.forEach(e => {
          let arr = []
          arr = arr.concat(JSON.parse(JSON.stringify(samplePricePeriod)))
          this.$set(e, 'pricePeriod', arr)
        })
      } else {

        let arr = [].concat(JSON.parse(JSON.stringify(samplePricePeriod)))

        this.$set(this.tempRowObj, 'pricePeriod', arr)
      }

      this.dialogFormVisible = false

    },

    generateWeights() {

      let weightForm = this.weightForm

      let step = parseFloat(weightForm.step)

      if (weightForm.genType == 'byNumber') {
        step = (parseFloat(weightForm.maxWeight) / parseFloat(weightForm.number))
      }

      let max = parseInt(weightForm.maxWeight)
      let arr = []
      let start = 0
      while (true) {

        if (start >= max) {
          arr.push({
            "showRemove": false,
            "value": max
          })
          break
        }

        arr.push({
          "showRemove": false,
          "value": start
        })

        start += step

        start = parseFloat(start.toFixed(3))
      }

      this.weightArray = arr

    },

    loadPriceVersionTags(priceVersionId) {
      let _this = this

      // 获取单位相关映射
      _this.$ajax({
        url: '/fms-api/product/PmsTransportPriceRpc/loadPriceTags.json',
        data: { "priceVersionId": priceVersionId },
        success: (res) => {
          if (res && res.data && res.data.rows) {
            _this.priceTagHistory = res.data.rows
          }
        }
      });
    },

    switchPriceVersion(priceTagId) {

      let _this = this
      // 获取单位相关映射
      _this.$ajax({
        url: '/fms-api/product/PmsTransportPriceRpc/loadPriceTagDetail.json',
        data: {
          "priceTagId": priceTagId
        },
        success: (res) => {
          if (res && res.data) {
            _this.formValue.transportMainPrice = res.data.transportMainPrice
            _this.formValue.additionPrices = res.data.additionPrices
            _this.$message({
              type: 'success',
              message: this.$t('tip_operate_success')
            })

            // 切换版本后 重新初始化
            this.initForm();
          }
        }
      });


    },


    getButtonLabel() {
      if (this.formValue.transportMainPrice.chargeType == 'VOLUME') {
        return this.$tt('label_pms_volume_range_cfg')
      }
      if (this.formValue.transportMainPrice.chargeType == 'WEIGHT' || this.formValue.transportMainPrice.chargeType == 'CAL_WEIGHT') {
        return this.$tt('label_pms_weight_range_cfg')
      }
      if (this.formValue.transportMainPrice.chargeType == 'DENSITY') {
        return this.$tt('label_pms_density_range_cfg')
      }
      if (this.formValue.transportMainPrice.chargeType == 'BOX') {
        return this.$tt('label_pms_gross_cargo_range_cfg')
      }
    },
    selectFile(e) {

      if (!e || e.length == 0) return
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      let reader = new FileReader();
      reader.onload = (e) => {
        const data = e.target.result

        new ExcelJS.Workbook().xlsx.load(data).then(workbook => {
          // 价卡
          if (workbook._worksheets[1]) {
            const excelData = []
            const worksheet = workbook.getWorksheet(1);
            worksheet.eachRow((row, rowNumber) => {
              excelData.push(row.values)
            });
            if (excelData.length == 0) return this.$message.error(this.$t('label_import_error'))
            this.excelDatahand(excelData)
          }
          // 操作费
          if (workbook._worksheets[2]) {
            const excelData = []
            const worksheet = workbook.getWorksheet(2);
            worksheet.eachRow((row, rowNumber) => {
              excelData.push(row.values)
            });
            if (excelData.length == 0) return this.$message.error(this.$t('label_import_error'))
            this.excelDatahandOperateFee(excelData)
          }
          // 进制
          if (workbook._worksheets[3]) {
            const excelData = []
            const worksheet = workbook.getWorksheet(3);
            worksheet.eachRow((row, rowNumber) => {
              excelData.push(row.values)
            });
            if (excelData.length == 0) return this.$message.error(this.$t('label_import_error'))
            this.excelDatahandbinary(excelData)
          }
        })
      };
      loading.close();
      reader.readAsArrayBuffer(e[0]);
    },
    // 处理导入后的数据
    excelDatahand(metadata) {
      let headData = metadata[0].slice(3, metadata[0].length)
      // 去掉数据中的数字和空格
      let headDataObj = []
      if (typeof headData[0] !== 'string') {
        this.$message.error(this.$t('tip_data_load_fail'))
        return
      }
      headData.forEach(item => {
        let split = item.split(' ')
        let numArr = split[1].split('-')
        headDataObj.push({
          type: split[0],
          start: numArr[0].replace(/\s/g, ""),
          end: numArr[1].replace(/\s/g, ""),
        })
      })


      // headDataObj.map((item, index) => {
      //   if (item.type === "续重") {
      //     headDataObj.unshift(headDataObj.splice(index, 1)[0]);
      //   }
      // })


      console.log(headDataObj)


      // 获取单个国家每个重量段的数据
      const setPricePeriod = (row) => {
        let pricePeriod = []
        for (let index = 0; index < headDataObj.length; index++) {
          const item = headDataObj[index];
          if (row[index + 3]) {
            pricePeriod.push({
              "start": item.start,
              "end": item.end,
              "price": Number(row[index + 3]),
              "startPrice": item.type === '首重' ? Number(row[index + 3]) : 0,
              "addPrice": item.type === '续重' ? Number(row[index + 3]) : 0,
              "customFirstWeight": '',
              "unit": "weight",
              "scale": '',
              "otherAttachPrice": ''
            })

          }
        }
        return pricePeriod
      }

      // this.formValue.transportMainPrice.priceConfigs = []
      console.log(metadata)
      console.log(this.formValue.transportMainPrice.priceConfigs)
      // 只导入对应区域数据
      metadata.forEach((item, index) => {
        if (index > 0) {
          this.formValue.transportMainPrice.priceConfigs.forEach((obj) => {
            if (item[1] === obj.areaCode) {
              this.$set(obj, 'pricePeriod', setPricePeriod(item))
              // return {
              //   areaId: obj.id,
              //   areaCode: obj.groupCode,
              //   areaName: obj.subareaName,
              //   countryCode: obj.countryCode,
              //   countryName: obj.countryName,
              //   singlePrice: 1,
              //   pricePeriod: setPricePeriod(item)
              // }
            }
          })
        }
      })

    },
    // 处理导入后的操作费
    excelDatahandOperateFee(metadata) {
      let headData = metadata[0].slice(3, metadata[0].length)
      // 去掉数据中的数字和空格
      let headDataObj = []
      if (typeof headData[0] !== 'string') {
        this.$message.error(this.$t('label_import_error'))
        return
      }
      headData.forEach(item => {
        let split = item.split(' ')
        let numArr = split[1].split('-')
        headDataObj.push({
          start: numArr[0].replace(/\s/g, ""),
          end: numArr[1].replace(/\s/g, ""),
        })
      })

      const setOperateFee = (row, pricePeriod) => {
        let value = null
        for (let index = 0; index < headDataObj.length; index++) {
          const item = headDataObj[index];
          if (item.start === pricePeriod.start && item.end === pricePeriod.end) {
            value = Number(row[index + 3]) || ''
            this.operateFeeConfig = true
            break
          }
        }
        return value
      }
      // 只导入对应区域数据
      metadata.forEach((item, index) => {
        if (index > 0) {
          this.formValue.transportMainPrice.priceConfigs.forEach((obj) => {
            if (item[1] === obj.areaCode) {
              obj.pricePeriod.forEach(pricePeriod => {
                pricePeriod.otherAttachPrice = setOperateFee(item, pricePeriod)
              })
            }
          })
        }
      })

    },
    // 处理导入后的进制
    excelDatahandbinary(metadata) {
      let headData = metadata[0].slice(3, metadata[0].length)
      // 去掉数据中的数字和空格
      let headDataObj = []
      if (typeof headData[0] !== 'string') {
        this.$message.error(this.$t('label_import_error'))
        return
      }
      headData.forEach(item => {
        let split = item.split(' ')
        let numArr = split[1].split('-')
        headDataObj.push({
          start: numArr[0].replace(/\s/g, ""),
          end: numArr[1].replace(/\s/g, ""),
        })
      })

      const setScale = (row, pricePeriod) => {
        let value = null
        for (let index = 0; index < headDataObj.length; index++) {
          const item = headDataObj[index];
          if (item.start === pricePeriod.start && item.end === pricePeriod.end) {
            value = Number(row[index + 3]) || ''
            this.binaryConfig = true
            break
          }
        }
        return value
      }
      // 只导入对应区域数据
      metadata.forEach((item, index) => {
        if (index > 0) {
          this.formValue.transportMainPrice.priceConfigs.forEach((obj) => {
            if (item[1] === obj.areaCode) {
              obj.pricePeriod.forEach(pricePeriod => {
                pricePeriod.scale = setScale(item, pricePeriod)
              })
            }
          })
        }
      })

    },
    weightArrayAdd(index) {
      let value = (this.weightArray[index].value + (index > 0 ? this.weightArray[index - 1].value : 0)) / 2
      this.weightArray.splice(index, 0, { showRemove: true, value: Number(value.toFixed(3)) })
      this.weightArray[index + 1].showRemove = false
    },
    // 取消进制配置和操作费配置时 数据清空
    configChange() {
      this.formValue.transportMainPrice.priceConfigs.forEach(item => {
        item.pricePeriod.forEach(item2 => {
          if (!this.binaryConfig) {
            this.$set(item2, 'scale', '')
          }
          if (!this.operateFeeConfig) {
            this.$set(item2, 'otherAttachPrice', '')
          }
          if (!this.firstWeightConfig) {
            this.$set(item2, 'customFirstWeight', '')
          }

        })
      })
    },
    // 下载模版
    downloadImportTemp() {
      window.open('http://kyb-bronze-public-oss.oss-cn-shenzhen.aliyuncs.com/default_template/product_price_import_1.xlsx')
    },


  }
};

</script>
<style lang="scss" scoped>
.price-cal-div-row {
  display: flex;
}

.price-cal-div-row .price-cal-col {
  width: 120px;
  text-align: center;
}

.price-cal-div-row div {
  margin-right: 8px;
  text-align: center;
}

.price-split-edit-row {
  /*display: flex;*/
  display: block;
}

.price-split-edit-col {
  display: block;
  width: 80px;
  float: left;
}

.price-split-edit-row .price-split-edit-line {
  width: 40px;
  height: 2px;
  border-top: 4px solid #DCDFE6;
  margin-top: 14px;
}

.price-split-edit-row .price-split-edit-arrow {
  width: 0px;
  height: 0px;
  margin-top: 8px;
  border-bottom: 8px solid transparent;
  border-top: 8px solid transparent;
  border-left: 8px solid #DCDFE6;
  font-size: 0;
  line-height: 0;
}

.line-weight-period-price-table .cell {
  font-size: 14px;
  padding-left: 0px;
  padding-right: 0px;
}

.price-edit-inner-input {
  text-align: center;
  height: 30px;
  line-height: 30px;
  font-size: 14px;
  border-radius: 4px;
  border: 1px solid #DCDFE6;
}

.no-clear-input-text .el-input__inner {
  padding-right: 0px;
}

.transprot-price-time-line .el-timeline-item__wrapper {
  top: -9px;
}

.flexuse {
  display: flex;
  min-width: 300px;

  flex-direction: column;
  /* //align-items: center; */
  padding-bottom: 10px;
  border: 1px solid #d9dfe7;
  border-right: none;

  &:last-of-type {
    border-right: 1px solid rgb(217, 223, 231);
  }

  >div:last-of-type {
    display: flex;
    padding: 0 10px;
    align-items: flex-end;
    gap: 8px;
    width: 100%;
  }
}

.weightRangeWrap{
  padding: 0px 6px 0px 6px;
  position: relative;
  .weightRangeInput{
    width: 40px;
    font-size: 14px;
    text-align: center;
    >>> .el-input__inner{
      border: none !important;
      padding: 0 !important;
      text-align: center;
    }
  }
}


</style>
